package com.service.abolishing.controller;

import com.service.abolishing.dto.OpUserInfoDto;
import com.service.abolishing.dto.UserDto;
import com.service.abolishing.dto.UserLoginRecordDto;
import com.service.abolishing.entity.ManageInfo;
import com.service.abolishing.entity.UserLoginRecord;
import com.service.abolishing.service.ManageInfoService;
import com.service.abolishing.service.OperateInfoService;
import com.service.abolishing.service.UserLoginRecordService;
import com.service.config.dto.MailBean;
import com.service.config.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import static com.service.abolishing.controller.ManageInfoController.clearCache;
import static com.service.config.constant.Constant.*;

/**
 * 运营人员管理表(OperateInfo)表控制层
 *
 * @author makejava
 * @since 2021-08-10 16:14:26
 */
@RestController
@RequestMapping("operateInfo")
@Api(value = "运营人员管理接口",tags = "运营人员管理接口")
public class OperateInfoController {
    /**
     * 服务对象
     */
    @Resource
    private OperateInfoService operateInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ManageInfoService manageInfoService;
    @Resource
    private UserLoginRecordService userLoginRecordService;
    /**
     * 通过主键查询单条数据
     *
     * @param opUserInfoDto
     * @return 单条数据
     */
    @PostMapping(value = "auth",produces="application/json")
    @ApiOperation(value = "统一登录")
    @ResponseBody
    public Result customerLogin(@RequestBody OpUserInfoDto opUserInfoDto) throws Exception {
        HashMap map = new HashMap();
        opUserInfoDto = operateInfoService.queryAllByNameAndPassword(opUserInfoDto);
        String token = UserTokenManager.generateToken(opUserInfoDto.getId());
        redisUtil.set(token,4, JsonXMLUtils.obj2json(opUserInfoDto),2);
        map.put("Token",token);
        return Result.ok().setData(map);
    }
    /**
     * 客服退出登录
     *
     * @param cloudAuthToken
     * @return 单条数据
     */
    @PostMapping(value = "loginOut",produces="application/json")
    @ApiOperation(value = "客服退出登录")
    @ResponseBody
    public Result customerLogin(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            if (redisUtil.exist(cloudAuthToken)) {
                redisUtil.delete(cloudAuthToken);
                return Result.ok();
            }
        }
        return Result.ok();
    }
    /**
     * 客服退出登录
     *
     * @param cloudAuthToken
     * @return 单条数据
     */
    @GetMapping(value = "customerLoginUserRecord",produces="application/json")
    @ApiOperation(value = "用户登录记录")
    @ResponseBody
    public Result customerLoginUserRecord(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                          @RequestParam("userId") String userId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            UserLoginRecord userLoginRecord = new  UserLoginRecord();
            userLoginRecord.setUserId(userId);
            long countOnlineTime = 0;
            List< UserLoginRecord> userLoginRecordList = new ArrayList<>();
             // 大屏服务
            userLoginRecordList = userLoginRecordService.queryAll(userLoginRecord);
            if (userLoginRecordList != null) {
                for (UserLoginRecord userLoginRecord1 : userLoginRecordList ) {
                    countOnlineTime += userLoginRecord1.getOnlineTime();
                }
            }
            UserLoginRecordDto userLoginRecordDto = new UserLoginRecordDto();
            userLoginRecordDto.setUserId(userId);
            userLoginRecordDto.setOnlineTime(countOnlineTime);
            userLoginRecordDto.setUserLoginRecordList(userLoginRecordList);
            return Result.ok().setData(userLoginRecordDto);
        }
        return Result.ok();
    }
    /**
     * 通过主键查询单条数据
     * 销号 或者封号
     * @return 单条数据
     */
    @GetMapping(value = "isLogout",produces="application/json")
    @ApiOperation(value = "销号或者封号")
    @ResponseBody
    public Result customerLogin(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                @RequestParam("userId") String userId,
                                @RequestParam("isLogout") Boolean isLogout) throws Exception {
        if (redisUtil.exist(cloudAuthToken)) { // 销号 或者封号
            ManageInfo userInfo = new ManageInfo();
            userInfo.setId(userId);
            MailBean mailBean = new MailBean();
            mailBean.setSubject("封号提示");
            mailBean.setRecipient(userInfo.getEMail());
            mailBean.setContent(IS_LOGOUT);
            if (isLogout) {
                userInfo.setStatus(2); // 封号

            }else{
                userInfo.setStatus(3); // 销号
            }
            manageInfoService.update(userInfo);
            manageInfoService.sendMail(mailBean);
            Set<String> strings = redisUtil.redisLike(userId);
            clearCache(strings, redisUtil); //清除缓存
            return Result.ok();
        }else {
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
    }
    /**
     * 通过主键查询单条数据
     * 销号 或者封号
     * @return 单条数据
     */
    @GetMapping(value = "relieve",produces="application/json")
    @ApiOperation(value = "解除封号")
    @ResponseBody
    public Result relieve(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                          @RequestParam("userId") String userId,
                          @RequestParam("isLogout") Boolean isLogout) throws Exception {
        if (redisUtil.exist(cloudAuthToken)) { // 销号 或者封号
            ManageInfo userInfo = new ManageInfo();
            userInfo.setId(userId);
            MailBean mailBean = new MailBean();
            mailBean.setSubject("账号解封提醒");
            mailBean.setRecipient(userInfo.getEMail());
            mailBean.setContent(SEND_RELIVE_INFO);
            // 默认大屏服务销号 或者封号
            if (isLogout) {
                userInfo.setStatus(0); // 封号
            }
            manageInfoService.update(userInfo);
            Set<String> strings = redisUtil.redisLike(userId);
            clearCache(strings, redisUtil); //清除缓存
            return Result.ok();
        }else {
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
    }
    /**
     * 查询在线用户
     *
     * @param
     * @return
     */
    @GetMapping(value = "queryOnlineUser",produces="application/json")
    @ApiOperation(value = "查询在线用户")
    @ResponseBody
    public Result queryOnlineUser()  {
        List<ManageInfo> userInfos = manageInfoService.queryAllByLimit(0,999999);
        List<UserDto> userDtoArrayList = new ArrayList<>();
        userInfos.forEach(userInfo -> {
            Set<String> strings= redisUtil.redisLike(userInfo.getId());
            if (strings != null){
                strings.stream().forEach(s -> {
                    String value = redisUtil.getValue(s);
                    try {
                        UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                        long dateMin = DateUtil.getDateMin(DateUtil.datetoString(userDto.getDate()), DateUtil.datetoString(new Date()));
                        userDto.setOnlineTime(dateMin);
                        userDtoArrayList.add(userDto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });

            }
        });
        return Result.ok().setData(userDtoArrayList);
    }
    /**
     * 点击账号名可查询用户个人信息
     *
     * @param
     * @return
     */
    @GetMapping(value = "queryOnlineByUser",produces="application/json")
    @ApiOperation(value = "查询用户个人信息")
    @ResponseBody
    public Result queryOnlineByUser(@RequestParam("manageId") String manageId)  {
        return Result.ok().setData(manageInfoService.queryByUserId(manageId));
    }
    /**
     * 用户踢下线
     *
     * @param
     * @return
     */
    @GetMapping(value = "offLine",produces="application/json")
    @ApiOperation(value = "用户踢下线")
    @ResponseBody
    public Result queryOnlineUser(@RequestParam("manageId") String manageId)  {
        Set<String> strings= redisUtil.redisLike(manageId);
        clearCache(strings,redisUtil);
        return Result.ok();
    }
    /**
     * 查询所有用户
     *
     * @param
     * @return
     */
    @GetMapping(value = "queryAllUser",produces="application/json")
    @ApiOperation(value = "查询所有用户")
    @ResponseBody
    public Result queryAllUser()  {
        List<ManageInfo> userInfos = manageInfoService.queryAllByLimit(0,999999);
        return Result.ok().setData(ModelMapperUtil.strictMapList(userInfos, UserDto.class));
    }
}
